<?php
/**
 * 汇友科技
 * @copyright (c) 2017 http://www.huiyou365.net All rights reserved.
 * @author: Creatint <creatint@163.com>
 */
namespace Common\Model;

use Think\Model as TPModel;
use Think\Page;
use Closure;

class Model extends TPModel{
    /**
     * 计数器
     * @var int
     */
    protected $counter = 0;

    /**
     * 分页数据
     * @var null
     */
    protected $page = null;

    /**
     * 获取列表，原生数据.
     *
     * @param null $query
     * @param bool $field 需要的字段
     * @param bool $showPage 是否显示分页数据
     * @return mixed
     */
    public function get($query = null, $field = true, $order = 'sort DESC, updated_at DESC', $showPage = true, Closure $closure = null ){
        $map = array();

        // 设置id条件
        isset($query['id']) && $query['id']>0 && $map['id'] = $query['id'];
        // 排除id条件
        unset($query['id']);
        // 遍历条件
        foreach($query as $k=>$v){
            $map[$k] = $v;
        }

        // 是否显示分页数据
        if ( $showPage ) {
            $res = $this
                ->where($map)
                ->order($order)
                ->page(I('get.p',0) . ',' . C('LIST_ROWS'))
                ->field($field)
                ->select();
            $count = $this->where($map)->count();
            $this->page = show_page(new Page($count, C('LIST_ROWS')));
        } else {
            $res = $this
                ->where($map)
                ->order($order)
                ->field($field)
                ->select();
        }

        return $res;
    }


    /**
     * 获取单条数据.
     *
     * @param null $query
     * @param bool $field
     * @param Closure $closure
     * @return mixed
     */
    public function info($query = null, $field = true, Closure $closure = null){
        $map = array();

        // 设置id条件
        isset($query['id']) && $map['id'] = $query['id'];
        // 排除id条件
        unset($query['id']);
        // 遍历条件
        foreach($query as $k=>$v){
            $map[$k] = $v;
        }

        // 获取单条数据
        $res = $this
            ->where($map)
            ->field($field)
            ->find();

        // 有闭包则传入闭包
        if ( $closure ) {
            $res = $closure($res);
        }

        return $res;
    }


    public function getPage(){
        return $this->page;
    }


    public function remove($id = null,$pid = null){
        if ( !$id && !$pid ) {
            $this->error = '待删除项为空';
            return false;
        }
        if ($id) {
            $map[] = [
                'id'=>[
                    'IN',
                    (array)$id
                ]
            ];
        }
        if ($pid) {
            $map[] = [
                'pid'=>[
                    'IN',
                    (array)$pid
                ]
            ];
        }
        if ( $this->where($map)->delete() ) {
            S('DB_CONFIG', null);
            return true;
        } else {
            return false;
        }
    }


    /**
     * 更新数据.
     *
     * @param $data
     * @return bool
     */
    public function update($data = null){
        // 默认使用$_POST
        if( !$data ) {
            $data = $_POST;
        }

        // 程序出口值,0:失败, >1:成功, 以位运算的或运算来修改其值,新增成功则返回id值,因此在控制器中应该以$_POST['id']为主
        $res = 1;

        // 验证数据,验证失败则 res = 0
        $res &= (bool)($data = $this->create($data)) ;

        // 如果id存在,则更新,保存失败则 res = 0
        $res && $data['id'] && ($res &= (bool)$this->save($data));

        // 如果id不存在,则新增,新增成功则 res = id（返回ID）
        $res && !$data['id'] && ($id = $this->add($data)) && ($res = $id);

        // 程序出口
        return $res;
    }

    public function position($pos, $category = null, $limit = null, $field = true, $child = true){
        $map = $this->listMap($category, 0, $pos, $child);
        $limit>0 && $this->limit($limit);

        /* 读取数据 */
        $res = $this->field($field)->where($map)->order('sort DESC, updated_at DESC')->select();
        return $res;
    }


    /**
     * 设置where查询条件
     * @param  number  $category 分类ID
     * @param  number  $pos      推荐位
     * @param  integer $status   状态
     * @return array             查询条件
     */
    private function listMap($category, $status = 0, $pos = null, $child = null){
        /* 设置状态 */
        $map = array('status' => $status);

        /* 设置分类 */
        if(!is_null($category)){
            if(is_numeric($category)){
                if ( $child && $children = child_category($category,'id') ) {
                    $map['category_id'] = [
                        'in',
                        array_merge((array)$children, (array)$category)
                    ];
                } else {
                    $map['category_id'] = $category;
                }
            } else {
                if ( $child && $children = child_category($category,'id') ) {
                    $map['category_id'] = [
                        'in',
                        array_merge((array)$children, str2arr($category))
                    ];
                } else {
                    $map['category_id'] = array('in', str2arr($category));
                }
            }
        }



//        $map['created_at'] = array('lt', NOW_TIME);

        /* 设置推荐位 */
        if(is_numeric($pos)){
            $map[] = "position & {$pos} = {$pos}";
        }


        return $map;
    }

    public function counter(){
        $this->counter++;
        return $this->counter;
    }
    public function getCounter(){
        return $this->counter;
    }
}

function child_category($category_id,$field = true){
    $Category = D('Category');
    $list = $Category->where("pid=$category_id")->getField($field,true);
    return $list;
}
